﻿using WebApp.BLL.Base;
using WebApp.DAL;
using WebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using WebApp.ViewModels.Dict;
using WebApp.Common.Caching;

namespace WebApp.BLL.Manage
{
    public class S_dictService : BaseService<S_dict>
    {
        #region (DAL)Repository
        /// <summary>
        /// 检查数据字典
        /// </summary>
        internal S_dicttypeRepository dicttypeRepository = new S_dicttypeRepository();
        #endregion

        #region 构造

        public S_dictService() : base(new S_dictRepository()) { }

        #endregion

        #region PageList

        public List<S_dict> PageList(int pageindex, int pagesize, string searchkey, string dtype, string sort, string order, out int rowscount)
        {
            var T = this.CurrentRepository.Entities.Where(p => p.Isdeleted == "0");
            //根据属性名实现动态排序 

            if (string.IsNullOrEmpty(sort))
            {
                T = T.OrderBy(p => p.Typecode).ThenBy(p => p.Sort).ThenBy(p => p.Code);
            }
            else
            {
                T = base.SortList(T, sort, order == "asc" ? true : false);
            }

            //查询条件
            if (!string.IsNullOrEmpty(searchkey))
            {
                T = T.Where(p => p.Code.Contains(searchkey) || p.Name_cn.Contains(searchkey)
                             || p.Name_en.Contains(searchkey));
            }
            if (!string.IsNullOrEmpty(dtype))
            {
                T = T.Where(p => p.Typecode == dtype);
            }

            //返回记录数
            rowscount = T.Count();
            //返回分页结果

            return this.CurrentRepository.PageList(T, pageindex, pagesize).ToList();
        }
        #endregion

        #region CacheList

        ///// <summary>
        ///// 从缓存获取所有s_dict
        ///// </summary>
        ///// <returns></returns>
        //public List<s_dict> CacheList()
        //{
        //    var cachekey = "s_dict";

        //    var result = new MemoryCacheManager().Get<List<s_dict>>(cachekey, 60, () =>
        //    {
        //        return this.CurrentRepository.Entities
        //            .Where(p => p.Isdeleted == "0")
        //            .OrderBy(p => p.Typecode)
        //            .ThenBy(p => p.Sort)
        //            .ThenBy(p => p.Code)
        //            .ToList();
        //    });

        //    return result;
        //}

        ///// <summary>
        ///// 更新数据后，刷新缓存
        ///// </summary>
        //public void RefreshCache()
        //{
        //    var cachekey = "s_dict";

        //    var list = this.CurrentRepository.Entities
        //            .Where(p => p.Isdeleted == "0")
        //            .OrderBy(p => p.Typecode)
        //            .ThenBy(p => p.Sort)
        //            .ThenBy(p => p.Code)
        //            .ToList();

        //    new MemoryCacheManager().Remove(cachekey);
        //    new MemoryCacheManager().Set(cachekey, list, 60);
        //}

        public List<S_dict> GetCache(string typecode)
        {
            var cachekey = string.Format("S_dict_{0}", typecode);

            var result = new MemoryCacheManager().Get<List<S_dict>>(cachekey, 60, () =>
            {
                return this.CurrentRepository.Entities
                    .Where(p => p.Isdeleted == "0" && p.Typecode == typecode)
                    .OrderBy(p => p.Typecode)
                    .ThenBy(p => p.Sort)
                    .ThenBy(p => p.Code)
                    .ToList();
            });

            return result;
        }

        public void RefreshCache(string typecode)
        {
            var cachekey = string.Format("S_dict_{0}", typecode);

            var list = this.CurrentRepository.Entities
                    .Where(p => p.Isdeleted == "0" && p.Typecode == typecode)
                    .OrderBy(p => p.Typecode)
                    .ThenBy(p => p.Sort)
                    .ThenBy(p => p.Code)
                    .ToList();

            new MemoryCacheManager().Remove(cachekey);
            new MemoryCacheManager().Set(cachekey, list, 60);
        }

        public void RemoveCache(string typecode)
        {
            var cachekey = string.Format("S_dict_{0}", typecode);
            new MemoryCacheManager().Remove(cachekey);
        }

        #endregion

        #region Save

        public bool Save(S_dict item)
        {
            if (item.Id == 0)
            {
                item.Isdeleted = "0";
                this.CurrentRepository.Add(item, false);
            }
            else
            {
                this.CurrentRepository.Update(item, false);
            }

            //提交事物
            this.CurrentRepository.Save();

            //更新缓存
            this.RefreshCache(item.Typecode);

            return true;
        }

        #endregion

        #region Exist

        public bool ExistName(int id, string typecode, string name_cn)
        {
            if (id == 0)
            {
                return this.CurrentRepository.Entities.FirstOrDefault(p => p.Typecode == typecode && p.Name_cn == name_cn) != null;
            }
            else
            {
                return this.CurrentRepository.Entities.FirstOrDefault(p => p.Id != id && p.Typecode == typecode && p.Name_cn == name_cn) != null;
            }
        }

        #endregion

        #region DeleteById

        public bool DeleteById(string ids)
        {
            foreach (string id in ids.Split(','))
            {
                if (string.IsNullOrEmpty(id)) continue;
                //逻辑删除
                var item = this.CurrentRepository.Find(Convert.ToInt32(id));
                item.Isdeleted = "1";
                this.CurrentRepository.Update(item);

                //更新缓存
                this.RemoveCache(item.Typecode);
            }
            this.CurrentRepository.Save();

            ////更新缓存
            //this.RefreshCache();

            return true;
        }

        #endregion

        #region GetByTypecode

        public IList<S_dict> ListByTypecode(string typecode)
        {
            //return this.CacheList().Where(p => typecode.Equals(p.Typecode, StringComparison.OrdinalIgnoreCase)).ToList();
            return this.GetCache(typecode);
        }

        #endregion

        #region GetCodeByName

        public string GetCodeByName(string typecode, string name)
        {
            if (string.IsNullOrEmpty(name)) return "";

            var list = this.GetCache(typecode);
            var item = list.FirstOrDefault(p => name.Equals(p.Name_cn, StringComparison.OrdinalIgnoreCase)
                || name.Equals(p.Name_en, StringComparison.OrdinalIgnoreCase)
                || name.Equals(p.Code, StringComparison.OrdinalIgnoreCase));
            if (item == null)
            {
                return string.Empty;
            }
            else
            {
                return item.Code;
            }
        }

        #endregion

        #region GetNames

        /// <summary>
        /// 根据多个字典代码获取名称（用逗号分隔）
        /// </summary>
        /// <param name="typecode"></param>
        /// <param name="codelist"></param>
        /// <returns></returns>
        public string GetNames(string typecode, IEnumerable<string> codelist)
        {
            var list = this.GetCache(typecode);
            var T = list.Where(p => codelist.Contains(p.Code));

            return string.Join(",", T.Select(p => p.Name_cn));
        }

        #endregion

        #region GetName

        /// <summary>
        /// 根据字典代码获取名称
        /// </summary>
        /// <param name="typecode"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetName(string typecode, string code)
        {
            //var T = this.CurrentRepository.Entities.Where(p => p.Isdeleted == "0");
            //var T = this.GetCache(typecode).AsQueryable();

            //if (!string.IsNullOrEmpty(typecode))
            //{
            //    T = T.Where(p => p.Typecode.Equals(typecode));
            //}
            //if (!string.IsNullOrEmpty(code))
            //{
            //    T = T.Where(p => p.Code.Equals(code));
            //}
            if (string.IsNullOrEmpty(typecode))
            {
                return "";
            }

            var item = this.GetCache(typecode).FirstOrDefault(p => p.Code == code);
            if (item == null)
            {
                return string.Empty;
            }

            return item.Name_cn;
        }

        public string GetName(S_dict item)
        {
            if (item == null)
            {
                return string.Empty;
            }

            return item.Name_cn;
        }

        #endregion

        #region GetCodeSelectList

        public SelectList GetCodeSelectList(string typeCode, string selectedValue = "")
        {
            var list = this.CurrentRepository.Entities
                .Where(p => p.Typecode == typeCode && p.Isdeleted == "0")
                .OrderBy(p => p.Sort)
                .ThenBy(p => p.Sort);

            return new SelectList(list, "Code", "Code", selectedValue);
        }

        #endregion

        #region GetNameSelectList

        public SelectList GetNameSelectList(string typeCode, string selectedValue = "")
        {
            //var list = this.CurrentRepository.Entities
            //    .Where(p => p.Typecode == typeCode && p.Isdeleted == "0")
            //    .OrderBy(p => p.Sort)
            //    .ThenBy(p => p.Sort);
            var list = this.GetCache(typeCode);

            return new SelectList(list, "Name_cn", "Name_cn", selectedValue);
        }

        #endregion

        #region GetSelectList

        /// <summary>
        /// 获取数据字典下拉框数据源
        /// </summary>
        /// <param name="typeCode"></param>
        /// <param name="selectedValue"></param>
        /// <returns></returns>
        public SelectList GetSelectList(string typeCode, string selectedValue = "")
        {
            //var list = this.CurrentRepository.Entities
            //    .Where(p => p.Typecode == typeCode && p.Isdeleted == "0")
            //    .OrderBy(p => p.Sort)
            //    .ThenBy(p => p.Sort);
            var list = this.GetCache(typeCode);

            if (typeCode == "PartType")
            {
                //零件品种
                list = list.OrderBy(p => p.Name_cn).ToList();
            }
            else
            {
                //其他
                list = list.OrderBy(p => p.Sort).ThenBy(p => p.Code).ToList();
            }

            return new SelectList(list, "Code", "Name_cn", selectedValue);
        }

        public SelectList GetSelectList(IEnumerable<S_dict> list, string selectedValue = "")
        {
            return new SelectList(list, "Code", "Name_cn", selectedValue);
        }

        #endregion

        #region SearchList

        public List<S_dict> SearchList(string typeCode, string s)
        {
            var list = this.GetCache(typeCode);

            return list.Where(p => (p.Name_cn.StartsWith(s) || p.Name_hk.StartsWith(s))).OrderBy(p => p.Sort).ToList();
        }

        #endregion

    }
}
